package com.example.controller;

import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Apply;
import com.example.entity.Artwork;
import com.example.entity.Student;
import com.example.entity.College;
import com.example.service.ApplyService;
import com.example.service.ArtworkService;
import com.example.service.CollegeService;
import com.example.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static com.example.common.enums.ResultCodeEnum.APPLY_ALREDAY_ERROR;
import static com.example.common.enums.ResultCodeEnum.ARTWORK_ALREDAY_ERROR;

/**
 * 作品信息表前端操作接口
 **/
@RestController
@RequestMapping("/artwork")
public class ArtworkController {
    private static final List<String> PRIZE_ORDER = Arrays.asList("特等奖", "一等奖", "二等奖", "三等奖", "参与奖");

    @Resource
    private ArtworkService artworkService;
    @Resource
    private StudentService studentService;
    @Resource
    private CollegeService collegeService;
    @Autowired
    private ApplyService applyService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Artwork artwork) {
        //查询是否审核通过
        Integer contestId = artwork.getContestId();
        Integer studentId = artwork.getStudentId();
        Apply apply = new Apply();
        apply.setContestId(contestId);
        apply.setStudentId(studentId);
        apply.setAppstatus("已通过");
        List<Apply> applies = applyService.selectAll(apply);
        if (applies == null || applies.isEmpty()) {
            return Result.error(ResultCodeEnum.ARTWORK_COMMIT_ERROR);
        }
        //先查询是否提交过
        Artwork artwork1 = new Artwork();
        artwork1.setContestId(artwork.getContestId());
        artwork1.setStudentId(artwork.getStudentId());
        List<Artwork> artworks = artworkService.selectAll(artwork1);
        if (artworks!=null && artworks.size()>0) {
            return Result.error(ARTWORK_ALREDAY_ERROR);
        }

        artworkService.add(artwork);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        artworkService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        artworkService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody Artwork artwork) {
        artworkService.updateById(artwork);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Artwork artwork = artworkService.selectById(id);
        return Result.success(artwork);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Artwork artwork) {
        List<Artwork> list = artworkService.selectAll(artwork);
        return Result.success(list);
    }

    @GetMapping("/getByContestId/{contestId}")
    public Result getByContestId(@PathVariable Integer contestId) {
        List<Artwork> artworkList = artworkService.getByContestId(contestId);
        return Result.success(artworkList);
    }
    //竞赛奖项管理，横坐标是姓名，纵坐标是成绩的折线图
    @GetMapping("/getartworkBycontest/{contestId}")
    public ResponseEntity<Result> getartworkBycontest(@PathVariable Integer contestId) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> scoreMap = new TreeMap<>();
        try {
            List<Artwork> all = artworkService.getByContestId(contestId);
            for (Artwork artwork : all) {
                String studentName = artwork.getStudentName();
                Integer score = artwork.getScore();
                if (studentName != null && score != null) {
                    scoreMap.put(studentName, score);
                }
            }

            // 将 scoreMap 转换为 List 并按成绩降序排序
            List<Map.Entry<String, Integer>> scoreList = new ArrayList<>(scoreMap.entrySet());
            scoreList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
            resultMap.put("text", "成绩统计");
            resultMap.put("subtext", "统计维度：分数");
            resultMap.put("name", "分数");
            resultMap.put("data", scoreList);
            return new ResponseEntity<>(Result.success(resultMap), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Result.error(ResultCodeEnum.valueOf("获取作品成绩统计信息时出现异常")), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //查询某个竞赛结果
    @GetMapping("/list")
    public Result list(@RequestParam("page") int page, @RequestParam(value = "contestId", required = false) Integer contestId) {
        int pageSize = 10; // 每页显示数量
        int offset = (page - 1) * pageSize;

        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        if (contestId != null) {
            params.put("contestId", contestId);
        }

        List<Artwork> artworkList = artworkService.getArtworkList(params);
        int total = artworkService.getTotalCount(params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", artworkList);
        result.put("total", total);

        return Result.success(result);
    }
    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Artwork artwork,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Artwork> page = artworkService.selectPage(artwork, pageNum, pageSize);
        return Result.success(page);
    }

    @GetMapping("/getcollegePie")
    public Result getcollegePie() {
        // 初始化 college 为 null

        Map<String, Object> resultMap = new HashMap<>();
        // 假设 Student 类中有 getCollegeId 方法获取学院 ID
        Map<String, Integer> collegeCountMap = new HashMap<>();
        List<Artwork> all = artworkService.selectAll(new Artwork());
        for(Artwork artwork: all){
            Integer studentId = artwork.getStudentId();
            Student student = studentService.selectById(studentId);
            // 这里可以对时间进行处理，例如打印、存储或其他操作，但目前代码未做此操作
            Integer collegeId = student.getCollegeId();
            College colllege = collegeService.selectById(collegeId);
            if (collegeCountMap.containsKey(colllege.getName())) {
                // 如果学院 ID 已在 Map 中，将计数加 1
                collegeCountMap.put(colllege.getName(), collegeCountMap.get(colllege.getName()) + 1);
            } else {
                // 如果学院 ID 不在 Map 中，添加该学院 ID 并将计数初始化为 1
                collegeCountMap.put(colllege.getName(), 1);
            }
        }
        System.out.println(collegeCountMap);
        resultMap.put("text","学院参赛获奖信息统计");
        resultMap.put("subtext","统计维度：竞赛人数");
        resultMap.put("name","人数");
        resultMap.put("data",collegeCountMap);
        return Result.success(resultMap);
    }

    @GetMapping("/getprizecount")
    public Result getprizecount() {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> prizeCountMap = new HashMap<>();
        try {
            List<Artwork> all = artworkService.selectAll(new Artwork());
            if (all != null) {
                for (Artwork artwork : all) {
                    if (artwork.getPrize() != null) {
                        String prizename = artwork.getPrize();
                        prizeCountMap.put(prizename, prizeCountMap.getOrDefault(prizename, 0) + 1);
                    }
                }
            }

            // 将 prizeCountMap 中的键值对提取到 List 中
            List<Map.Entry<String, Integer>> entryList = new ArrayList<>(prizeCountMap.entrySet());

            // 按指定奖项顺序排序
            entryList.sort((e1, e2) -> {
                String prize1 = e1.getKey();
                String prize2 = e2.getKey();
                int index1 = PRIZE_ORDER.indexOf(prize1);
                int index2 = PRIZE_ORDER.indexOf(prize2);

                if (index1 == -1 && index2 == -1) {
                    // 若两个奖项都不在指定顺序中，按字母顺序排序
                    return prize1.compareTo(prize2);
                } else if (index1 == -1) {
                    // 若 prize1 不在指定顺序中，prize2 在，prize1 排到后面
                    return 1;
                } else if (index2 == -1) {
                    // 若 prize2 不在指定顺序中，prize1 在，prize2 排到后面
                    return -1;
                } else {
                    // 若两个奖项都在指定顺序中，按指定顺序排序
                    return Integer.compare(index1, index2);
                }
            });

            // 将排序后的键值对存入 LinkedHashMap 以维持顺序
            LinkedHashMap<String, Integer> sortedPrizeCountMap = new LinkedHashMap<>();
            for (Map.Entry<String, Integer> entry : entryList) {
                sortedPrizeCountMap.put(entry.getKey(), entry.getValue());
            }

            resultMap.put("text", "获奖队伍人数统计");
            resultMap.put("subtext", "统计维度：队伍");
            resultMap.put("name", "队伍");
            resultMap.put("data", sortedPrizeCountMap);
            return Result.success(resultMap);
        } catch (Exception e) {
            return Result.success(null); // 可以根据实际情况返回更合适的错误信息
        }
    }

    @GetMapping("/getartworkcount")
    public Result getartworkcount() {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Integer> artworkCountMap = new HashMap<>();
        List<Artwork> all = artworkService.selectAll(new Artwork());
        for (Artwork artwork : all) {
            String student = artwork.getStudentName();
            if (student != null) {
                artworkCountMap.merge(student, 1, Integer::sum);
            }
        }
        System.out.println(artworkCountMap);
        resultMap.put("text", "作品统计");
        resultMap.put("subtext", "统计维度：个数");
        resultMap.put("name", "个数");
        resultMap.put("data", artworkCountMap);
        return Result.success(resultMap);
    }


}